<template>
  <div id="goodsDetail">
    <div style="margin: 50px 0"></div>
    <el-page-header @back="goBack" content="" style="margin-left: 20%"></el-page-header>
    <div style="width: 90%; margin: 0 auto; text-align: center">
      <img src="~@/images/logo.png" alt="" style=" width: 175px; height: 56px; transform: translateY(-50px)">
      <search style="display: inline-block"/>
    </div>
    <div style="border-bottom: 1px solid #c8baaa; margin: 0 0 50px 0"></div>
    <div class="container">
      <div class="left">
        <img :src="detail.goodsWantInfo.goodsWant.goodsWantImage" alt="">
      </div>
      <div class="right">
        <div style="text-align: center"><strong style="font-size: initial; color: initial">{{detail.goodsWantInfo.goodsWant.goodsWantName}}</strong></div>
        <div class="detail">
          <div><span style="margin-right: 40px">价格</span><span style="font-size: 22px; color: #e12228">￥{{detail.goodsWantInfo.goodsWant.goodsWantPrice}}</span><span style="float: right;">累计浏览{{detail.goodsWantInfo.goodsWant.browsedCount}}人</span></div><br>
          <div style="width: 68%; line-height: 40px">
            <span style="margin-right: 40px; float: left">促销</span>
            <span style="float: right; width: 380px">
              <span style="background-color: #c81623; color: white; padding: 2px;">加购价</span> 满999.00另加20.00元，或满1999.00另加30.00元，或满2999.00另加40.00元，即可在购物车换 购热销商品
            </span>
          </div>
          <div style="clear: both"></div>
          <div style="width: 68%; line-height: 30px">
            <span style="margin-right: 40px; float: left">描述</span>
            <span style="float: right; width: 380px">{{detail.goodsWantInfo.goodsWant.goodsWantInfo}}</span>
          </div>
          <div style="width: 1px;height: 1px; clear: both"></div>
        </div>
        <div style="padding: 20px"><span style="margin-right: 40px">库存</span>{{detail.goodsWantInfo.goodsWant.goodsWantCount}}件</div>
        <div style="padding: 20px"><span style="margin-right: 40px">数量</span><el-input-number v-model="needCount" :min="1" :max='detail.goodsWantInfo.goodsWant.goodsWantCount'></el-input-number></div>
        <div v-if="!!!detail.goodsWantInfo.favoriteId" class="collection"><button @click="collectionClick(detail.goodsWantInfo.favoriteId)" :disabled='detail.goodsWantInfo.goodsWant.goodsWantCount === 0'>加入收藏夹</button></div>
        <div v-else class="collection"><button @click="collectionClick(detail.goodsWantInfo.favoriteId)" :disabled='detail.goodsWantInfo.goodsWant.goodsWantCount === 0'>取消收藏</button></div>
        <!-- 只有在商品帖才会显示购买和购物车按钮 -->
        <div class="btns" v-if="realGoodsWant === 'g'"><el-button type="text" @click="open" :disabled='detail.goodsWantInfo.goodsWant.goodsWantCount === 0'>立即购买</el-button>
        <button @click="cartClick" :disabled='detail.goodsWantInfo.goodsWant.goodsWantCount === 0'><i class="el-icon-shopping-cart-2"></i>加入购物车</button></div>
      </div>
      <div style="width: 1px;height: 1px; clear: both"></div>
    </div>
    <div class="messages">
      <span>留言板：</span>
      <ul>
        <li v-for="items in detail.messageLists" :key="items.message.messageId">
          <span>{{items.username}}：</span>
          <div style="width: 80%; margin: 0 auto;">
            <p>{{items.message.content}}</p>
          </div>
          <p style="position: absolute; bottom: 10px; right: 20px; font-size: 13px; color: #666">{{items.message.messageFloor}}楼&nbsp;&nbsp;{{items.message.gmtCreate}}</p>
        </li>
        <li>
          <div style="margin-bottom: 20px; text-align: initial"><strong>发表留言</strong></div>
          <div style="margin-bottom: 20px">
            <textarea name="" id="" cols="30" rows="10" style="width: 70%" v-model="message"></textarea>
          </div>
          <el-button type="primary" round @click="messageClick">发表</el-button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import search from '@/components/home/search/search'
import {request} from '@/network/request'

export default {
  data() {
    return {
      needCount: 1,
      realGoodsWant: 'g',
      message: '',
      detail: {
        goodsWantInfo: {
          favoriteId: '',
          goodsWant: {
            goodsWantName: '',
            goodsWantInfo: '',
            goodsWantImage: '',
            browsedCount: '',
            goodsWantPrice: '',
            goodsWantCount: 1
          }
        },
        messageLists: [
          {username: '', message: {content: '', messageFloor: '', gmtCreate: ''}}
          
        ]
      }
    }
  },
  computed: {
    priceAll() {
      return this.detail.goodsWantInfo.goodsWant.goodsWantPrice * this.needCount
    }
  },
  components: {
    search
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    collectionClick(favoriteId) {
      if(!this.$store.state.isLogin) {
        this.$message({
          message: '您还未登录，请先登录！！',
          type: 'warning'
        })
        this.$router.push('/login')
      } else {
        // 点击收藏，向服务器发送请求
        let obj = JSON.stringify({
          goodsWantId: this.$store.state.goodsId,
          userId: this.$store.state.userId
        })
        request({
          url: '/favorite/addToFavorite',
          method: 'post',
          data: obj
        }).then(res => {
          // console.log(res);
          if(!!!favoriteId) {
            this.$message({
              message: '添加收藏夹成功！',
              type: 'success'
            })
          } else {
            this.$message({
              message: '取消收藏成功！',
              type: 'success'
            })
          }
          // 重新请求数据，更新页面数据
          let goodsWantId = this.$store.state.goodsId
          this.realGoodsWant = this.$store.state.goodsWantDetail
          request({
            // url: `/goods-want/searchGoodsInfo/${goodsWantId}`,
            url: `/goods-want/searchGoodsInfo`,
            method: 'get',
            params: {
              goodsWantId,
              userId: this.$store.state.userId
            }
          }).then(res => {
            // console.log(res);
            this.detail = res.data.data
          }).catch(err => {
            console.log(err);
          })
        }).catch(err => {
          console.log(err);
        })
      }
    },
    cartClick() {
      if(!this.$store.state.isLogin) {
        this.$message({
          message: '您还未登录，请先登录！！',
          type: 'warning'
        })
        this.$router.push('/login')
      } else {
        // 点击添加购物车，向服务器发送请求
        let obj = JSON.stringify({
          goodsWantId: this.$store.state.goodsId,
          needCount: this.needCount,
          userId: this.$store.state.userId
        })
        request({
          url: '/shoppingcart/addToCart',
          method: 'post',
          data: obj
        }).then(res => {
          // console.log(res);
          this.$message({
            message: '添加购物车成功！',
            type: 'success'
          })
        }).catch(err => {
          console.log(err);
        })
      }
    },
    open() {
      if(!this.$store.state.isLogin) {
        this.$message({
          message: '您还未登录，请先登录！！',
          type: 'warning'
        })
        this.$router.push('/login')
      } else {
        // 先发请求判断用户是否有支付密码
        request({
          url: `/user/buy/${this.$store.state.userId}`,
          method: 'get'
        }).then(res => {
          // 未设置支付密码
          if(!res.data.flag) {
            this.$message({
              message: '请先设置支付密码！',
              type: 'warning'
            })
            this.$router.push('/profile')
          // 设置了支付密码
          } else {
            return this.$prompt('请输入支付密码', `支付 ${this.priceAll}元`, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputType: 'password',
              inputPlaceholder: '请输入6位数字支付密码',
              inputPattern: /^\d{6}$/,
              inputErrorMessage: '请输入6位数字支付密码'
            })
          }
        }).then(({ value }) => {
          // 输入支付密码点击确定，向服务器发送请求
          let obj = JSON.stringify({
            userId: this.$store.state.userId,
            goodsWantId: this.$store.state.goodsId,
            needCount: this.needCount,
            paymentPassword: value
          })
          return request({
            url: '/user/buy',
            method: 'put',
            data: obj
          })
        }, () => {
          this.$message({
            type: 'warning',
            message: '取消购买'
          });
        }).then(res => {
          if(res && res.data.flag) {
            this.$message({
              type: 'success',
              message: '支付成功！'
            });
            this.detail.goodsWantInfo.goodsWant.goodsWantCount--
          }
          if(res && !res.data.flag) {
            this.$message({
              type: 'warning',
              message: res.data.message
            })
          }
        })
      }
      // this.$prompt('请输入支付密码', '支付', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   inputType: 'password',
      //   inputPlaceholder: '请输入6位数字支付密码',
      //   inputPattern: /^\d{6}$/,
      //   inputErrorMessage: '请输入6位数字支付密码'
      // }).then(({value}) => {
      //   console.log(value);
      // }, () => {
      //   this.$message({
      //     message: '取消购买',
      //     type: 'warning'
      //   })
      // })
    },
    messageClick() {
      if(!this.$store.state.isLogin) {
        this.$message({
          message: '您还未登录，请先登录！！',
          type: 'warning'
        })
        this.$router.push('/login')
      } else {
        if(this.message === '') {
          this.$message({
            message: '您还未输入任何评论！',
            type: 'warning'
          })
        } else {
          // 点击发表留言按钮，向服务器发送请求保存留言
          let messageFloor
          if(this.detail.messageLists.length > 0) {
            messageFloor = this.detail.messageLists[this.detail.messageLists.length-1].message.messageFloor + 1
          } else {
            messageFloor = 1
          }
          let obj = JSON.stringify({
            content: this.message,
            goodsWantId: this.$store.state.goodsId,
            messageFloor,
            userId: this.$store.state.userId
          })
          request({
            url: '/message/saveMessage',
            method: 'post',
            data: obj
          }).then(res => {
            console.log(res);
            if(res.data.flag) {
              this.$message({
                message: '发表成功',
                type: 'success'
              })
              // 发表成功，更改页面数据
              this.detail.messageLists.push({
                username: this.$store.state.username,
                message: {content: this.message, messageFloor, gmtCreate: res.data.data.GmtCreate}
              })
            }
          }).catch(err => {
            console.log(err);
          })
        }
      }
    }
  },
  mounted() {
    // 一进入到本页面，向服务器请求数据
    let goodsWantId = this.$store.state.goodsId
    this.realGoodsWant = this.$store.state.goodsWantDetail
    request({
      url: `/goods-want/searchGoodsInfo`,
      method: 'get',
      params: {
        goodsWantId,
        userId: this.$store.state.userId
      }
    }).then(res => {
      console.log(res);
      this.detail = res.data.data
    }).catch(err => {
      console.log(err);
    })
  },
  // 组件导航守卫
  // beforeRouteEnter(to, from, next) {
  //   next(vm => {
  //     if(from.path === '/home') {
  //       vm.realGoodsWant = vm.$store.state.goodsWant
  //     }
  //     if(from.path === '/search_result') {
  //       vm.realGoodsWant = vm.$store.state.searchGoodsWant
  //     }
  //     if(from.path === '/profile/shopcart') {
  //       vm.realGoodsWant = 'g'
  //     }
  //   })
  // }
}
</script>

<style scoped>
  #goodsDetail .container {
    width: 60%;
    /* height: 1000px; */
    margin: 0 auto;
    border: 1px solid #000;
  }

  #goodsDetail .container .left {
    float: left;
    margin-right: 20px;
    width: 418px;
  }

  #goodsDetail .container .left img {
    width: 418px;
    height: 418px;
  }

  #goodsDetail .container .right {
    float: left;
    color: #666;
    font-size: 13px;
    width: calc(100% - 438px);
  }

  #goodsDetail .container .right .detail {
    background-color: #fee9eb;
    margin: 10px 0;
    padding: 20px;
  }

  #goodsDetail .container .right button {
    padding: 7px 0;
    margin-right: 10px;
    font-size: 17px;
    cursor: pointer;
    width: 190px;
  }

   #goodsDetail .container .right button[disabled] {
     cursor: not-allowed;
  }

  #goodsDetail .container .right .collection {
    margin: 30px 50px;
  }

  #goodsDetail .container .right .collection button {
    background-color: #ffeded;
    color: #ff0036;
    border: 1px solid #ff0036;
  }

  #goodsDetail .container .right .btns {
    /* padding: 20px; */
    /* text-align: center; */
    margin-left: 50px;
  }

  #goodsDetail .container .right .btns button:first-child {
    background-color: #ffeded;
    color: #ff0036;
    border: 1px solid #ff0036;
  }

  #goodsDetail .container .right .btns button:last-child {
    background-color: #ff0036;
    color: #fff;
    border: 1px solid #ff0036;
  }

  #goodsDetail .messages {
    width: 50%;
    margin: 0 auto;
    margin-top: 20px;
  }

  #goodsDetail .messages ul li {
    height: 150px;
    border: 1px solid #e5e5e5;
    border-top: none;
    padding: 10px 20px;
  }

  #goodsDetail .messages ul li:first-of-type {
    border-top: 1px solid #e5e5e5;
  }

  #goodsDetail .messages ul li:not(:last-of-type) {
    position: relative;
  }

  #goodsDetail .messages ul li:last-of-type {
    height: 280px;
    text-align: center;
  }
</style>